﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Guoc.BigMall.WebService.Dto;
using Guoc.BigMall.WebService;
using Guoc.BigMall.Infrastructure.Caching;
using Guoc.BigMall.Infrastructure;

namespace Guoc.BigMall.WebService.Implement
{
    public class UserContextService : IUserContextService
    {
        ITokenService _tokenService;
        ICacheManager _cache;
        private const string CURRENT_USER = "Current_User";

        public UserContextService(ICacheManager cache, ITokenService tokenService)
        {
            this._cache = cache;
            _tokenService = tokenService;
        }

        public UserContext Current {
            get {
                var token= HttpContext.Current.Request.Headers["token"];
                if (!_tokenService.Validate(token)) {
                    throw new FriendlyException("账号已过期");
                }

                var data = _tokenService.GetData(token);
                var memberId = data[_tokenService.CurrentUserKey];              
                var cacheKey = UserContext.GetCacheKey(memberId);
                var user = _cache.Get<UserContext>(cacheKey);
                if (user == null)
                {
                    throw new FriendlyException("账号已过期");                  
                }
                return user;

            }       
        }
       
    }
}
